package dao

import (
	dom "a-common/domain"
	"a-demo/domain/entity"
	"strings"
	"sync"
)

var (
	senRoomDaoTemp *SenRoomDao
	senRoomDaoOnce sync.Once
)

type SenRoomDao struct{}

func NewSenRoomDao() *SenRoomDao {
	senRoomDaoOnce.Do(func() {
		senRoomDaoTemp = &SenRoomDao{}
	})
	return senRoomDaoTemp
}

// List 分页
func (m *SenRoomDao) List(args *entity.SenRoomDto, isExprot bool) (dom.PageVo, error) {
	// 构建查询条件
	query := pgCli.Table(&entity.SenRoom{}).Where("1 = 1")
	if args.RoomFloor != "" {
		query.And("room_floor = ?", args.RoomFloor)
	}
	if args.RoomNo != "" {
		query.And("room_no = ?", args.RoomNo)
	}
	if args.RoomName != "" {
		query.And("room_name = ?", args.RoomName)
	}
	if args.Status != "" {
		query.And("status = ?", args.Status)
	}
	if args.PageSize != 0 {
		query.Limit(args.PageSize, (args.PageNum-1)*args.PageSize)
	}

	// 查询
	var vPage dom.PageVo
	if isExprot {
		var rows []entity.SenRoomExportVo
		total, err := query.Asc("room_id").FindAndCount(&rows)
		if err != nil {
			return vPage, err
		}
		vPage.Rows = rows
		vPage.Total = total
	} else {
		var rows []entity.SenRoomPageVo
		total, err := query.Asc("room_id").FindAndCount(&rows)
		if err != nil {
			return vPage, err
		}
		vPage.Rows = rows
		vPage.Total = total
	}
	vPage.PageNum = args.PageNum
	vPage.PageSize = args.PageSize
	return vPage, nil
}

// Del 删
func (m *SenRoomDao) Del(ids string) (int64, error) {
	return pgCli.In("room_id", strings.Split(ids, `,`)).Delete(&entity.SenRoom{})
}

// Get 查
func (m *SenRoomDao) Get(id string) (entity.SenRoomVo, error) {
	var v entity.SenRoomVo
	_, err := pgCli.Table(&entity.SenRoom{}).ID(id).Get(&v)
	return v, err
}

// Add 增
func (m *SenRoomDao) Add(args *entity.SenRoomDto) (int64, error) {
	return pgCli.InsertOne(&entity.SenRoom{
		RoomFloor: args.RoomFloor,
		RoomNo:    args.RoomNo,
		RoomName:  args.RoomName,
		RoomSort:  args.RoomSort,
		Status:    args.Status,
		BaseStruct: dom.BaseStruct{
			CreatedBy: args.CreatedBy,
			UpdatedBy: args.CreatedBy,
			Remark:    args.Remark,
		},
	})
}

// Edit 改
func (m *SenRoomDao) Edit(args *entity.SenRoomDto) (int64, error) {
	return pgCli.ID(args.RoomId).Update(&entity.SenRoom{
		RoomFloor: args.RoomFloor,
		RoomNo:    args.RoomNo,
		RoomName:  args.RoomName,
		RoomSort:  args.RoomSort,
		Status:    args.Status,
		BaseStruct: dom.BaseStruct{
			UpdatedBy: args.UpdatedBy,
			Remark:    args.Remark,
		},
	})
}
